package admin

import (
	"SlowAdmin/controllers"
	"SlowAdmin/models"
	"encoding/json"
)

// RoleController 角色控制器
type RoleController struct {
	controllers.BaseController
}

var adminRoleModel = models.AdminRole{}

// @title 添加
func (c *RoleController) Store() {
	var data struct {
		Menus []int `json:"menus"`
	}
	json.Unmarshal(c.Ctx.Input.RequestBody, &data)
	json.Unmarshal(c.Ctx.Input.RequestBody, &adminRoleModel)

	var menus []models.AdminMenu
	for _, item := range data.Menus {
		var temp models.AdminMenu
		temp.Id = uint(item)
		menus = append(menus, temp)
	}
	adminRoleModel.Menus = menus

	err := adminRoleModel.Store()

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("添加成功", nil)
}

// @title 获取列表
func (c *RoleController) List() {
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 15)

	list, total := adminRoleModel.GetList(page, pageSize)

	c.Success("ok", controllers.Result{
		"list":      list,
		"total":     total,
		"page":      page,
		"page_size": pageSize,
	})
}

// @title 详情
func (c *RoleController) Find() {
	id := c.Ctx.Input.Param(":id")
	if id == "" {
		c.Fail("id不能为空", nil)
		return
	}

	c.Success("ok", adminRoleModel.GetOne(id))
}

// @title 更新
func (c *RoleController) Update() {
	var data struct {
		Menus []int `json:"menus"`
	}
	json.Unmarshal(c.Ctx.Input.RequestBody, &data)
	json.Unmarshal(c.Ctx.Input.RequestBody, &adminRoleModel)

	var menus []models.AdminMenu
	for _, item := range data.Menus {
		var temp models.AdminMenu
		temp.Id = uint(item)
		menus = append(menus, temp)
	}
	adminRoleModel.Menus = menus

	err := adminRoleModel.Update()

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("更新成功", nil)
}

// @title 删除
func (c *RoleController) Delete() {
	var data map[string]string
	json.Unmarshal(c.Ctx.Input.RequestBody, &data)

	err := adminRoleModel.Delete(data["ids"])

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("删除成功", nil)
}
